package com.hh.flex.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.hh.common.core.domain.BaseEntity;
import com.hh.common.exception.ServiceException;
import com.hh.common.utils.StringUtils;
import com.hh.security.utils.SecurityUtils;
import com.mybatisflex.annotation.InsertListener;

import java.util.Date;

/**
 * @description:  全局新增监听器
 * @author minliuhua
 * @date: 2023/5/2 22:53
 */
public class HhInsertListener implements InsertListener {

    @Override
    public void onInsert(Object object) {
        try {
            if (ObjectUtil.isNotNull(object)) {
                BaseEntity entity = (BaseEntity) object;
                Date date = ObjectUtil.isNotNull(entity.getCreateTime())
                        ? entity.getCreateTime() : new Date();
                entity.setCreateTime(date);
                entity.setUpdateTime(date);

                String username = StringUtils.isNotBlank(entity.getCreateBy())
                        ? entity.getCreateBy() : SecurityUtils.getUsernameNe();
                entity.setCreateBy(username);
                entity.setUpdateBy(username);
            }
        } catch (Exception e) {
            throw new ServiceException("新增自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }
}
